<script setup lang="ts" name="Codeview">
import { onBeforeRouteLeave } from "vue-router";
import { CODE_DATA_ENUM } from "@/views/tool/gen/const";
import { previewTableApi } from "@/api/tool/gen";

const { proxy } = getCurrentInstance();

const route = useRoute();

const codeData = ref([]);

// 激活项
const activeName = CODE_DATA_ENUM.domainJava;

// 激活项代码
const codeItemValue = ref('');

/** 预览按钮 */
function getPreview() {
  const tableId = route.params.tableId;

  previewTableApi(tableId).then(response => {
    codeData.value = [];
    for (let key in response.data) {
      let datakey = key.substring(key.lastIndexOf('/') + 1, key.indexOf('.vm'));
      let codeItem = { label: datakey, value: response.data[key] }
      codeData.value.push(codeItem);
      activeChange(CODE_DATA_ENUM.domainJava);
    }
  });
}

/** 激活项变更 */
function activeChange(value) {
  codeItemValue.value = codeData.value.find(item => item.label == value)?.value || " ";
}

/** 复制代码成功 */
function copyTextSuccess() {
  proxy.$modal.msgSuccess("复制成功");
}

/** 返回 */
function handleExit() {
  router.go(-1);
}

onBeforeRouteLeave(() => {
  useTagsViewStore().delView(<RouterRecord>route);
})

getPreview()
</script>

<template>
  <div class="app-container prev-box">
    <div class="back-item prev-item">
      <div class="table-top mb8">
        <div class="title title-left">
        </div>
        <el-button
            class="top-right-btn"
            icon="DocumentCopy"
            type="primary"
            plain
            v-copyText="codeItemValue"
            v-copyText:callback="copyTextSuccess"
        >复制
        </el-button>
        <el-button
            class="top-right-btn"
            icon="Back"
            type="warning"
            plain @click="handleExit"
        >返回
        </el-button>
      </div>
      <el-tabs v-model="activeName" @tab-change="activeChange">
        <el-tab-pane
            v-for="(item, index) in codeData"
            :label="item.label"
            :name="item.label"
            :key="index"
        >
          <pre class="code-box">{{ item.value }}</pre>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.prev-box {
  height: 100%;

  .prev-item {
    height: 100%;

    .el-tabs {
      height: 100%;

      :deep(.el-tabs__content) {
        height: calc(100% - 60px);
        overflow-y: auto;
      }
    }

    .code-box {
      overflow-x: auto;
      margin-top: 0;
    }
  }
}

.top-right-btn {
  z-index: 99;
}

:deep(.el-tabs) {
  margin-top: -40px !important;
}
</style>